package net.zhengxinyun.performance.service.indicators;

import com.sirdc.modules.utils.ObjectUtils;
import net.zhengxinyun.performance.Util.StringUtils;
import net.zhengxinyun.performance.Util.Util;
import net.zhengxinyun.performance.dto.ExcelDTO;
import net.zhengxinyun.performance.entity.CountryIndicatorsEntity;
import net.zhengxinyun.performance.entity.RolePerEntity;
import net.zhengxinyun.performance.entity.UserEntity;
import net.zhengxinyun.performance.filter.CountryIndicatorsFilter;
import net.zhengxinyun.performance.filter.CountryScoreFilter;
import net.zhengxinyun.performance.filter.DepartmentFilter;
import net.zhengxinyun.performance.mapper.Department.DepartmentEntityMapper;
import net.zhengxinyun.performance.mapper.Indicators.CountryIndicatorsEntityMapper;
import net.zhengxinyun.performance.mapper.Indicators.CountryScoreEntityMapper;
import net.zhengxinyun.performance.mapper.login.RolePerMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.interceptor.TransactionAspectSupport;

import java.util.*;
import java.util.stream.Collectors;

/**
 * @Auther: hyp
 * @Date: 2018/10/29 18:11
 */
@Service
public class CountryIndicatorsServiceImpl implements CountryIndicatorsService {

    private CountryIndicatorsEntityMapper countryIndicatorsEntityMapper;

    private CountryScoreEntityMapper countryScoreEntityMapper;

    @Autowired
    private DepartmentEntityMapper department;

    @Autowired
    private RolePerMapper rolePerMapper;

    @Autowired
    public CountryIndicatorsServiceImpl(CountryIndicatorsEntityMapper countryIndicatorsEntityMapper, CountryScoreEntityMapper countryScoreEntityMapper) {
        this.countryIndicatorsEntityMapper = countryIndicatorsEntityMapper;
        this.countryScoreEntityMapper = countryScoreEntityMapper;
    }

    @Override
    @Transactional
    public String delete(CountryIndicatorsEntity countryIndicatorsEntity) {
        int i;
        CountryIndicatorsEntity entity = countryIndicatorsEntityMapper.selectByPrimaryKey(countryIndicatorsEntity.getId());
        if ("一级指标".equals(entity.getIndexType())){
            CountryIndicatorsFilter countryIndicatorsFilter = new CountryIndicatorsFilter();
            countryIndicatorsFilter.setSuperiorIndexId(entity.getId().toString());
            List<CountryIndicatorsFilter> list =  countryIndicatorsEntityMapper.query(countryIndicatorsFilter);
            for (CountryIndicatorsFilter filter:list) {
               i =  countryIndicatorsEntityMapper.deleteByPrimaryKey(filter.getId());
                if (i == 0){
                    TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
                    return "下属指标删除失败，请联系管理员";
                }
                countryScoreEntityMapper.deleteByIndexId(filter.getId().toString());
            }
        }
        i =  countryIndicatorsEntityMapper.deleteByPrimaryKey(countryIndicatorsEntity.getId());
        if (i == 0){
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            return "删除失败，请联系管理员";
        }
        return "删除成功";
    }

    @Override
    public int update(CountryIndicatorsEntity countryIndicatorsEntity) {
        return countryIndicatorsEntityMapper.updateByPrimaryKeySelective(countryIndicatorsEntity);
    }

    @Override
    public int insert(CountryIndicatorsEntity countryIndicatorsEntity) {
        return countryIndicatorsEntityMapper.insert(countryIndicatorsEntity);
    }

    @Override
    public List<CountryIndicatorsFilter> query(CountryIndicatorsFilter countryIndicatorsFilter) {
        return countryIndicatorsEntityMapper.query(countryIndicatorsFilter);
    }

    @Override
    public Integer queryForCount(CountryIndicatorsFilter countryIndicatorsFilter) {
        return countryIndicatorsEntityMapper.queryForCount(countryIndicatorsFilter);
    }

    @Override
    public void setIdByName(String name, String dateTime, CountryIndicatorsEntity countryIndicatorsEntity) {
        Map<String, Object> map = new HashMap<>();
        map.put("name", name);
        map.put("dateTime", dateTime);
        String sysId = countryIndicatorsEntityMapper.getIdByIndexName(map);
        countryIndicatorsEntity.setSuperiorIndexId(sysId);
    }

    /**
     * 分数录入页查询
     *
     * @param countryIndicatorsFilter//?0.
     * @return
     */
    @Override
    public List<CountryIndicatorsFilter> querySecondIndex(CountryIndicatorsFilter countryIndicatorsFilter, UserEntity userEntity) {
        if ("4".equals(countryIndicatorsFilter.getAudit())) {
            countryIndicatorsFilter.setAudit(null);
        }
        //应前端要求，给我状态值5就是搜索全部
        if ("5".equals(countryIndicatorsFilter.getAudit())) {
            countryIndicatorsFilter.setAudit("");
        }
        //countryIndicatorsFilter.setDateTime();
        List<CountryIndicatorsFilter> filterList = countryIndicatorsEntityMapper.queryByTwoTable(countryIndicatorsFilter);
        StringBuffer str = new StringBuffer();
        CountryScoreFilter countryScoreFilter = new CountryScoreFilter();
        List<CountryIndicatorsFilter> copyList = new ArrayList<>();

        HashMap<String,Object> departMap = departMap();
        HashMap<String,String> nameToCode= (HashMap<String, String>) departMap.get("name");
        HashMap<String,String> codeToName= (HashMap<String, String>) departMap.get("code");

        for ( CountryIndicatorsFilter item: filterList)
        {
            item.setLeadUnitName(codeToName.get(item.getLeadUnit()) );
           // item.setRespUnitName(codeToName.get(item.getResponsibilityUnit()));
            item.setDateTime(countryIndicatorsFilter.getMonthTime());
        }
        if("admin".equals(userEntity.getUserPermissions()))
        {
            return  filterList;
        }

        RolePerEntity role  = rolePerMapper.selectByPrimaryKey(userEntity.getRoleid());
        String index ="";
        if(ObjectUtils.isNotBlank(role))
        {
            index  = role.getCityIndex();
        }else {
            index = userEntity.getCityIndex();
        }

        HashMap<String,Object> map = Util.getIndexIdMap(index);
        List<CountryIndicatorsFilter> fList  = new ArrayList<>();
        for (CountryIndicatorsFilter item: filterList ){

            String id1 = item.getId().toString();
            Object id2 = map.get(id1);
            if(ObjectUtils.isBlank(id2))
            {
                continue;
            }
            if(id1.equals(id2.toString()))
            {
                fList.add(item);
            }


        }


        //在循环中要去除list中的元素用迭代器，否则会报错。
   /*     Iterator<CountryIndicatorsFilter> it = filterList.iterator();
        while (it.hasNext()) {
            CountryIndicatorsFilter filter = it.next();
            if (StringUtils.isBlank(filter.getMainUnit())){
                copyList.add(filter);
                it.remove();
                continue;
            }
        }*/
        /*CountryIndicatorsFilter countryIndictorsFilter = new CountryIndicatorsFilter();
        for (CountryIndicatorsFilter c:copyList) {
            countryIndictorsFilter.setSuperiorIndexId(c.getId().toString());
            List<CountryIndicatorsFilter> cList = countryIndicatorsEntityMapper.query(countryIndictorsFilter);
            filterList.addAll(cList);
        }
        for (CountryIndicatorsFilter filter:filterList) {
          *//*  if (StringUtils.isNotBlank(filter.getSuperiorIndexId())) {
                CountryIndicatorsEntity firstIndex = countryIndicatorsEntityMapper.selectByPrimaryKey(Long.parseLong(filter.getSuperiorIndexId()));
                str.setLength(0);
                str.append(firstIndex.getIndexName());
                str.append("(" + firstIndex.getWeight() + ")");
                filter.setSuperiorIndexId(str.toString());
            }*//*
            countryScoreFilter.setIndicatorsId(filter.getId().toString());
        }*/
        return fList;
    }

    /**
     * 根据传进来的一级指标返回对应的二级指标的map
     * @param list
     * @return
     */
    public List<Map<String, Object>> getIndexMap(List<CountryIndicatorsFilter> list) {
        List<Map<String, Object>> indexList = new ArrayList<>();
        CountryIndicatorsFilter countryIndicatorsFilter = new CountryIndicatorsFilter();
        List<CountryIndicatorsFilter> copyList = new ArrayList<>();
        for (CountryIndicatorsFilter filter : list) {
            HashMap indexMap = new HashMap();
            indexMap.put("firstName", filter);
            countryIndicatorsFilter.setIndexType("");
            countryIndicatorsFilter.setSuperiorIndexId(filter.getId().toString());
            List<CountryIndicatorsFilter> secondIndexList = query(countryIndicatorsFilter);
            Iterator<CountryIndicatorsFilter> it = secondIndexList.iterator();
            while (it.hasNext()) {
                CountryIndicatorsFilter c = it.next();
                if (StringUtils.isBlank(c.getLeadUnit())) {
                    copyList.add(c);
                    it.remove();
                }
            }
            for (CountryIndicatorsFilter f:copyList) {
                countryIndicatorsFilter.setSuperiorIndexId(f.getId().toString());
                List<CountryIndicatorsFilter> sonList = query(countryIndicatorsFilter);
                secondIndexList.addAll(sonList);
            }
            indexMap.put("secondIndex", secondIndexList);
            indexList.add(indexMap);
        }
        return indexList;
    }

    /**
     * \
     *
     * @param countryIndicatorsFilter
     * @return
     */
    @Override
    public List<CountryIndicatorsFilter> queryByTwoTable(CountryIndicatorsFilter countryIndicatorsFilter) {
        return countryIndicatorsEntityMapper.queryByTwoTable(countryIndicatorsFilter);
    }

    public int queryForAuditCount(CountryIndicatorsFilter countryIndicatorsFilter) {
        int i = countryIndicatorsEntityMapper.queryForAuditCount(countryIndicatorsFilter);
        return i;
    }

    @Override
    public CountryIndicatorsEntity queryById(Long id) {
        return countryIndicatorsEntityMapper.selectByPrimaryKey(id);
    }

    @Override
    public List<CountryIndicatorsFilter> queryForAudit(CountryIndicatorsFilter countryIndicatorsFilter) {
        if ("4".equals(countryIndicatorsFilter.getAudit())) {
            countryIndicatorsFilter.setAudit(null);
        }
        //应前端要求，给我状态值5就是搜索全部
        if ("5".equals(countryIndicatorsFilter.getAudit())) {
            countryIndicatorsFilter.setAudit("");
        }
        List<CountryIndicatorsFilter> filterList = countryIndicatorsEntityMapper.queryForAudit(countryIndicatorsFilter);
        StringBuffer str = new StringBuffer();
        List<CountryIndicatorsFilter> copyList = new ArrayList<>();
        CountryScoreFilter countryScoreFilter = new CountryScoreFilter();
        //在循环中要去除list中的元素用迭代器，否则会报错。
        Iterator<CountryIndicatorsFilter> it = filterList.iterator();
        while (it.hasNext()) {
            CountryIndicatorsFilter filter = it.next();
            if (StringUtils.isBlank(filter.getMainUnit())){
                copyList.add(filter);
                it.remove();
                continue;
            }
        }
        CountryIndicatorsFilter countryIndictorsFilter = new CountryIndicatorsFilter();
        for (CountryIndicatorsFilter c:copyList) {
            countryIndictorsFilter.setSuperiorIndexId(c.getId().toString());
            List<CountryIndicatorsFilter> cList = countryIndicatorsEntityMapper.query(countryIndictorsFilter);
            filterList.addAll(cList);
        }
        for (CountryIndicatorsFilter filter:filterList) {
            if (StringUtils.isNotBlank(filter.getSuperiorIndexId())) {
                CountryIndicatorsEntity firstIndex = countryIndicatorsEntityMapper.selectByPrimaryKey(Long.parseLong(filter.getSuperiorIndexId()));
                str.setLength(0);
                str.append(firstIndex.getIndexName());
                str.append("(" + firstIndex.getWeight() + ")");
                filter.setSuperiorIndexId(str.toString());
            }
            countryScoreFilter.setIndicatorsId(filter.getId().toString());
        }
        return filterList;
    }



    public  HashMap<String,Object> departMap ()
    {
        HashMap<String,Object> map = new HashMap<>();
        /**
         * 所有部门
         */
        List<DepartmentFilter> departlist  = department.query(new DepartmentFilter());
        HashMap<String,String> nameToCode = new HashMap<>();
        HashMap<String,String> codeToName = new HashMap<>();
        for(DepartmentFilter item: departlist)
        {
            nameToCode.put(item.getDepartAddr(),item.getDepartcode());
            codeToName.put(item.getDepartcode(),item.getDepartAddr());
        }

        map.put("code",codeToName);
        map.put("name",nameToCode);

        return map;
    }


    /**
     * 批量保存数据
     * @param list
     * @param datetime
     * @return
     */
    @Override
    public int saveExcelCityIndex(List<ExcelDTO> list, String datetime) {
        List<CountryIndicatorsEntity> oneIndexList  = new ArrayList<>();
        List<CountryIndicatorsEntity>  twoIndexList  = new ArrayList<>();

        int i =1;
        for (ExcelDTO dto : list) {

            CountryIndicatorsEntity oneIndex  = new CountryIndicatorsEntity();
            CountryIndicatorsEntity twoIndex  = new CountryIndicatorsEntity();

            twoIndex.setIndexName(dto.getCell0());
            twoIndex.setDateTime(datetime);
            if(StringUtils.isNumeric(dto.getCell1()))
            {
                twoIndex.setWeight(Integer.parseInt(dto.getCell1()));
            }else {
                twoIndex.setWeight(0);
            }

            twoIndex.setLeadUnit(dto.getCell23());
            twoIndex.setLeadUnitName(dto.getName23());
            twoIndex.setResponsibilityUnit(dto.getCell24());

            twoIndex.setIndexType("二级指标");
            twoIndex.setSort(i);
            twoIndex.setAudit("1");
            twoIndex.setSuperiorIndexId(dto.getCell4());
            i++;
            twoIndexList.add(twoIndex);

            //oneIndex.setSort();
            oneIndex.setIndexType("一级指标");
            oneIndex.setIndexName(dto.getCell4());
            oneIndex.setDateTime(datetime);
            oneIndex.setAudit("1");
            oneIndexList.add(oneIndex);

        }

        //保存之前先删掉
        countryIndicatorsEntityMapper.deleteOldIndex(datetime);
        //一级指标去重
        oneIndexList = oneIndexList.stream().collect(
                Collectors.collectingAndThen(
                        Collectors.toCollection(
                                () -> new TreeSet<>(Comparator.comparing(CountryIndicatorsEntity::getIndexName))
                        ),ArrayList::new
                )

        );
        int onecode = countryIndicatorsEntityMapper.batchSaveCityIndex(oneIndexList);
        if (onecode==0)
        {
            return  0;
        }
        Map<String,String> oneIndexMap = oneIndexList.stream().collect(Collectors.toMap(o -> o.getIndexName(),o -> o.getId().toString()));

        for (CountryIndicatorsEntity entity : twoIndexList) {
            if(oneIndexMap.containsKey(entity.getSuperiorIndexId()))
            {
                entity.setSuperiorIndexId(oneIndexMap.get(entity.getSuperiorIndexId()));
            }

        }

         //保存 二级指标
        int y =countryIndicatorsEntityMapper.batchSaveCityIndex(twoIndexList);

        if(y==0)
        {
            return  0;
        }
        return 1;
    }
}
